package models

import (
	"database/sql"
	"github.com/jinzhu/gorm"
	"kop/modules/mail/entity"
	"kop/pb"
	"time"
)

func AutoMigrate(dB *gorm.DB) {

	dB.AutoMigrate(new(entity.Mail))
}

func CreateSystemMail(dB *gorm.DB, roleID int32, title, content string, attachment *pb.Award) error {

	var mail = entity.Mail{
		RoleID:     roleID,
		FromType:   pb.MailFrom_System,
		Title:      title,
		Content:    content,
		Attachment: sql.NullString{Valid: false},
	}

	if attachment != nil {
		mail.AttachmentStruct = &pb.Attachment{
			Award:    attachment,
			Received: false,
		}
	}

	return dB.Create(&mail).Error
}

func CreateGMMail(dB *gorm.DB, roleID int32, title, content string, attachment *pb.Award) {

	var mail = entity.Mail{
		RoleID:     roleID,
		FromType:   pb.MailFrom_GM,
		Title:      title,
		Content:    content,
		Attachment: sql.NullString{},
	}

	if attachment != nil {
		mail.AttachmentStruct = &pb.Attachment{
			Award:    attachment,
			Received: false,
		}
	}

	if err := dB.Create(&mail).Error; err != nil {
		panic(err)
	}
}

func GetMails(dB *gorm.DB, roleID, page, pageNum int32) []entity.Mail {

	var mails []entity.Mail
	if err := dB.Where(entity.Mail{RoleID: roleID}).Order("id DESC").Limit(pageNum).Offset((page - 1) * pageNum).Find(&mails).Error; err != nil {
		panic(err)
	}

	return mails
}

func GetMail(dB *gorm.DB, roleID, ID int32) (entity.Mail, error) {

	var mail entity.Mail

	var err = dB.Where(entity.Mail{RoleID: roleID}).First(&mail, ID).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		panic(err)
	}

	return mail, err
}

//
func DelBeforeDay(dB *gorm.DB, roleID int32, timestamp time.Time) error {

	var ids []int32
	dB.Model(entity.Mail{}).Where("created_at < ?", timestamp).Where(entity.Mail{RoleID: roleID}).Limit(100).Pluck("id", &ids)

	if len(ids) > 0 {
		return dB.Delete(entity.Mail{}, ids).Error
	}

	return nil
}

func Read(dB *gorm.DB, roleID, ID int32) error {

	var where = entity.Mail{ID: ID, RoleID: roleID}
	return dB.Model(where).Where(where).Updates(entity.Mail{Read: true}).Error
}

func Delete(dB *gorm.DB, roleID int32, IDs []int32) error {

	var where = entity.Mail{RoleID: roleID}
	return dB.Where(where).Delete(where, IDs).Error
}

func Save(dB *gorm.DB, mail *entity.Mail) error {

	return dB.Save(mail).Error
}
